package com.lxhll.personnel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxhll.personnel.dao.PositionDao;
import com.lxhll.personnel.entity.Employee;
import com.lxhll.personnel.entity.Position;
import com.lxhll.personnel.service.EmployeeService;
import com.lxhll.personnel.service.PositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * (Position)表服务实现类
 *
 * @author makejava
 * @since 2021-07-18 01:06:38
 */
@Service("positionService")
public class PositionServiceImpl extends ServiceImpl<PositionDao,Position> implements PositionService {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private EmployeeService employeeService;

    @Override
    public Position getPositionById(Integer id) {
        Object position=redisTemplate.opsForValue().get("position_"+id);
        if (position == null) {
            position = this.baseMapper.selectById(id);
            redisTemplate.opsForValue().set("position_" + id, position, 1, TimeUnit.HOURS);
        }
        return (Position)position;
    }

    @Override
    public boolean removePositionByIds(Integer[] ids) {
        //如果岗位下有员工，则不能删除部门
        for(int id:ids){
            if(employeeService.count(new QueryWrapper<Employee>().eq("position_id",id))!=0){
                return false;
            }
        }
        this.removeByIds(Arrays.asList(ids));
        for(int id:ids){
            redisTemplate.delete("position_"+id);
        }
        return true;
    }

    @Override
    public boolean updatePositionById(Position position) {
        this.updateById(position);
        redisTemplate.opsForValue().set("position_" + position.getId(), position, 1, TimeUnit.HOURS);
        return true;
    }
}
